type TDate = 'h' | 'w' | 'd' | 'm' | 's';
type TExpire = `${number}${TDate}`;
interface IStorage {
  value: any;
  key: string;
  expire?: TExpire;
}

interface IStorageUtil {
  set: (data: IStorage) => void;
  get: (key: string) => any;
  delete: (key: string) => void;
  processExpire: (expire: TExpire, date: any) => void;
}
const storageUtil: IStorageUtil = {
  set(data: IStorage) {
    if (data.expire) {
      const date = { expire: 0 };
      data?.expire && this.processExpire(data.expire, date);
      localStorage.setItem(data.key, JSON.stringify({ expire: date.expire, value: data.value }));
    } else {
      localStorage.setItem(data.key, JSON.stringify(data.value));
    }
  },
  get(key: string) {
    let res = localStorage.getItem(key) as any;
    res && (res = JSON.parse(res));

    console.log(res?.expire, new Date().getTime(), key);

    if (res?.expire && res.expire < new Date().getTime()) {
      localStorage.removeItem(key);
      res = null;
    }
    return res;
  },
  delete(key: string) {
    localStorage.removeItem(key);
  },
  processExpire(expire: TExpire, date: { expire: number }) {
    const match = expire.match(/^(\d+)([a-zA-Z]+)$/);
    if (!match) {
      date.expire += new Date().getTime();
      return;
    }
    const time = match[1]; // 时间部分
    const timerUnit: TDate = match[2].toLocaleLowerCase() as TDate; // 单位部分（转小写）
    switch (timerUnit) {
      case 's':
        date.expire = Number(time) * 1000;
        break;
      case 'm':
        date.expire = Number(time) * 1000 * 60;
        break;
      case 'h':
        date.expire = Number(time) * 1000 * 60 * 60;
        break;
      case 'd':
        date.expire = Number(time) * 1000 * 60 * 60 * 24;
        break;
      case 'w':
        date.expire = Number(time) * 1000 * 60 * 60 * 24 * 7;
        break;
    }
    date.expire += new Date().getTime();
  },
};

export default storageUtil;
